package com.abc.wy.aop;

import com.abc.wy.fdp.utils.HttpUtils;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;


@Aspect
@Component
public class LogAndMonitorAop {

    final  Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("execution(public * com.abc.wy.fdp.controller..*.*(..))")
    public void requestPointcut(){}

    @Around("requestPointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        HttpServletRequest request = HttpUtils.getHttpServletRequest();
        Long startTime = System.currentTimeMillis();
        Object result = point.proceed();

        if(request == null) {
            return result;
        }

        Long endTime = System.currentTimeMillis();
        Long costTime = endTime - startTime;

        String requestUrl = request.getRequestURL().toString();
        String clientIP = HttpUtils.getIpAddress(request);
        //获取本地的IP地址
        InetAddress address = InetAddress.getLocalHost();
        String serverIP = address.getHostAddress();
        String requestBody = JSONObject.toJSONString(point.getArgs());
        String responseBody = JSONObject.toJSONString(result);

        // TODO 如果返回为文件或者返回结果很长则截断

        logger.info("costTime: {}, clientIP: {}, requestIP: {}, serverIP:{}, requestBody: {}, responseBody: {}",
                costTime, requestUrl, clientIP, serverIP, requestBody, responseBody);

        // TODO 增加监控上报

        return result;
    }
}

